 package com.opgea.crm.web.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.opgea.crm.common.SetupsAttributeQualifier;
import com.opgea.crm.common.SetupsModuleQualifier;
import com.opgea.crm.common.constant.ApplicationConstant;
import com.opgea.crm.common.util.DateUtil;
import com.opgea.crm.common.vo.IssueDashboardVo;
import com.opgea.crm.domain.entities.Issue;
import com.opgea.crm.domain.entities.SetupsValue;
import com.opgea.crm.domain.entities.security.CrmUser;
import com.opgea.crm.domain.modal.JsonModelMap;
import com.opgea.crm.services.EmployeeService;
import com.opgea.crm.services.IssueService;
import com.opgea.crm.services.OpportunityService;
import com.opgea.crm.services.ProjectDetailsService;
import com.opgea.crm.services.QualifierService;
import com.opgea.crm.services.SetupService;
import com.opgea.crm.web.form.IssueTopForm;
import com.opgea.crm.web.modal.LoggedUser;

@Controller
@RequestMapping(value="searchIssueDashboard") 
public class ProjectIssueController {

	Logger logger =  Logger.getLogger(ProjectIssueController.class);
	
	@Autowired
	OpportunityService opportunityService; 
	@Autowired
	IssueService issueService;
	@Autowired
	SetupService setupService;
	@Autowired
	QualifierService qualifierService;
	@Autowired
	EmployeeService employeeService;
	@Autowired
	ProjectDetailsService projectDetailsService;

    // Dashboard grid method
	@RequestMapping(method= RequestMethod.GET,value= "issueByProjectId")
	public @ResponseBody
	Map<String, List<IssueDashboardVo>> issueByProjectId(
					@RequestParam(required=false) Long projectId,
					@RequestParam(required= false)Long priorityId, 
					@RequestParam(required= false) Long assigntoId,HttpServletRequest request){
		Map<String, List<IssueDashboardVo>> issue = null;
		
		if (projectId != null && projectId == 0)
			projectId = null;
		
		if (priorityId != null && priorityId == 0)
			priorityId = null;
		if (assigntoId != null && assigntoId == 0)
			assigntoId = null;
		   alert("no Record Found");
		
		logger.debug("IssueDashboardController >>issueByProjectId");
		List<IssueDashboardVo> list = issueService.issueByProjectId(projectId, priorityId, assigntoId, null);
		issue = new HashMap<String, List<IssueDashboardVo>>();
		issue.put("data", list);
		return issue;
	}
	
	private void alert(String string) {
		// TODO Auto-generated method stub
		
	}

	// Bottom or project level Grid method
	@RequestMapping(method = RequestMethod.GET, value="findAllByProjectId")
	public @ResponseBody
	Map<String,Object> findAllByProjectId(@RequestParam(required=false,value="issueGridProjectId") Long issueGridProjectId) 
	{
		logger.debug("ProjectIssueController >> showIssueList");
		if(issueGridProjectId != null){
			List<IssueDashboardVo>  Issues = issueService.findAllByProjectId(issueGridProjectId);
			return JsonModelMap.success().data(Issues);
		}else{
			return JsonModelMap.success(); 
		}
	}
	
	  //My Issue List Grid Method
	 
	 @RequestMapping(method = RequestMethod.GET, value = "issueForm")
		public @ResponseBody
		Map<String, List<IssueDashboardVo>> issueForm (@RequestParam(required = false) Long projectId,
													@RequestParam(required = false) Long priorityId,
													@RequestParam(required= false) Long assigntoId,HttpServletRequest request) {
			Map<String, List<IssueDashboardVo>> issue = null;
 
			if (projectId != null && projectId == 0)
				projectId = null;
			if (priorityId != null && priorityId == 0)
				priorityId = null;
			if (assigntoId != null && assigntoId == 0)
				assigntoId = null;
			CrmUser user=LoggedUser.getUser(request);
			List<IssueDashboardVo> list = this.issueService.issueByProjectId(projectId, priorityId, assigntoId, user);
			issue = new HashMap<String, List<IssueDashboardVo>>();
			issue.put("data", list); 
			return issue;
		}
	 
	 
	 @RequestMapping(method = RequestMethod.GET, value = "issueDropDownList")
		public @ResponseBody
		Map<String, List<SetupsValue>> issueDropDownList(@RequestParam(required = false) String operation,
														@RequestParam(required = false) Long projectId) {

			SetupsValue setupsValue = new SetupsValue(ApplicationConstant.COMBO_VALUE,ApplicationConstant.COMBO_CAPTION_ALL);
			return populateIssueList(projectId, operation, setupsValue);
		}
	 
	 // Details Issue Code
	 
	 @RequestMapping(method = RequestMethod.GET, value = "detailsDropDownList")
		public @ResponseBody
		Map<String, List<SetupsValue>> detailsDropDownList(@RequestParam(required = false) String operation,
															@RequestParam(required = false) Long projectId) {
			return populateIssueList(projectId, operation, null);
		}

		private Map<String, List<SetupsValue>> populateIssueList(Long projectId,
															   String operation,
															   SetupsValue setupsValue) {
			
			Map<String, List<SetupsValue>> list = new HashMap<String, List<SetupsValue>>(); 
			List<SetupsValue> setupsValues = null;
			if (projectId != null && operation.equalsIgnoreCase("members")) {
				if (projectId == 0)
					projectId = null; 
				setupsValues = this.issueService.allProjectAndMembers(projectId);   
			}
			if (operation.equalsIgnoreCase("projects"))
				setupsValues = this.issueService.allProjects();
			
			if (operation.equalsIgnoreCase("category")) 
				setupsValues = this.setupService.listSetupValue(SetupsModuleQualifier.Issue.ordinal(),
																SetupsAttributeQualifier.Category.ordinal()); 
			
			if (operation.equalsIgnoreCase("status"))
				setupsValues = this.setupService.listSetupValue(SetupsModuleQualifier.Issue.ordinal(),
																SetupsAttributeQualifier.Status.ordinal());
			if (operation.equalsIgnoreCase("priority")) 
				setupsValues = this.setupService.listSetupValue(SetupsModuleQualifier.Issue.ordinal(),
																SetupsAttributeQualifier.Priority.ordinal());
			if (operation.equalsIgnoreCase("complexity"))
				setupsValues = this.setupService.listSetupValue(SetupsModuleQualifier.Issue.ordinal(),
																SetupsAttributeQualifier.Complexity.ordinal());

			if (operation.equalsIgnoreCase("resolution"))
				setupsValues = this.setupService.listSetupValue(SetupsModuleQualifier.Issue.ordinal(),
																SetupsAttributeQualifier.Resolution.ordinal());
			

			if (setupsValue != null)
				setupsValues.add(setupsValue);
				list.put("data", setupsValues);
			return list;
		}
		
		
		// Save Issues Method
		
		@RequestMapping(method = RequestMethod.POST, value = "saveIssue")
		public @ResponseBody
		Long saveIssue(@RequestBody IssueTopForm issueTopForm, HttpServletRequest request) {
			Issue issue=formToEntity(issueTopForm,new Issue(),request);
			Long id= this.issueService.create(issue);
			return id;  
		}
		
		
		private Issue formToEntity(IssueTopForm issueTopForm,Issue issue,HttpServletRequest request)
		{
		   CrmUser user=LoggedUser.getUser(request);
		   issue.setCreatedBy(user);
		   issue.setId(issueTopForm.getIssueId());
	       issue.setIssueName(issueTopForm.getDetailsissueName());
		   issue.setIssueReason(issueTopForm.getDetailsissueReason());
		   issue.setModuleId(issueTopForm.getDetailsModule());
		   if(issueTopForm.getDetailsCategoryId()!=null)
		   issue.setCategory(setupService.findById(new Long(issueTopForm.getDetailsCategoryId())));
		   if(issueTopForm.getDetailsStatusId()!=null)
		   issue.setStatus(setupService.findById(new Long(issueTopForm.getDetailsStatusId())));
		   if(issueTopForm.getDetailsPriorityId()!=null)
		   issue.setPriority(setupService.findById(new Long(issueTopForm.getDetailsPriorityId())));
		   if(issueTopForm.getDetailsComplexityId()!=null)
		   issue.setComplexity(setupService.findById(new Long(issueTopForm.getDetailsComplexityId())));
		   if(issueTopForm.getDetailsResolutionId()!=null)
		   issue.setResolution(setupService.findById(new Long(issueTopForm.getDetailsResolutionId())));
		   issue.setTargetDate(DateUtil.stringToDate(issueTopForm.getDetailsTargetDate()));
		   issue.setResolvedDate(DateUtil.stringToDate(issueTopForm.getDetailsResolvedDate()));
		   issue.setCreatedAt(new Date());
		   if(issueTopForm.getDetailsProjectId()!=null)
				issue.setProject(this.projectDetailsService.find(issueTopForm.getDetailsProjectId()));
		   if(issueTopForm.getDetailsAssignedToId()!=null)
				issue.setAssignedTo(this.employeeService.find(issueTopForm.getDetailsAssignedToId()));
		   
		   return issue;
		 
		}
		
		//Update Issues Method
		@RequestMapping(method=RequestMethod.POST,value="updateIssue")
		public @ResponseBody
		Long updateIssue(@RequestBody IssueTopForm issueTopForm,HttpServletRequest request)
		{
			Issue issue=this.issueService.findIssueById(issueTopForm.getIssueId());
			if(issue!=null)
			{
				CrmUser user=LoggedUser.getUser(request);
				issue.setCreatedBy(user);
			    issue.setIssueName(issueTopForm.getIssueName());
				issue.setIssueReason(issueTopForm.getIssueReason());  
				issue.setModuleId(issueTopForm.getIssueModule());
			    if(issueTopForm.getIssueCategoryId()!=null)
			    issue.setCategory(setupService.findById(new Long(issueTopForm.getIssueCategoryId())));
			    if(issueTopForm.getIssueStatusId()!=null)
			    issue.setStatus(setupService.findById(new Long(issueTopForm.getIssueStatusId())));
			    if(issueTopForm.getIssuePriorityId()!=null)
			    issue.setPriority(setupService.findById(new Long(issueTopForm.getIssuePriorityId())));
			    if(issueTopForm.getIssueComplexityId()!=null)
			    issue.setComplexity(setupService.findById(new Long(issueTopForm.getIssueComplexityId())));
			    if(issueTopForm.getIssueResolutionId()!=null)
			    issue.setResolution(setupService.findById(new Long(issueTopForm.getIssueResolutionId())));
			    if(issueTopForm.getIssueAssignedToId()!=null)
			    issue.setAssignedTo(this.employeeService.find(issueTopForm.getIssueAssignedToId()));
			   
			    issue.setTargetDate(DateUtil.stringToDate(issueTopForm.getTargetDate()));
			    issue.setResolvedDate(DateUtil.stringToDate(issueTopForm.getDateResolved())); 
			    issue.setCreatedAt(new Date()); 
			    if(issueTopForm.getIssueProjectId()!=null)
					issue.setProject(this.projectDetailsService.find(issueTopForm.getIssueProjectId())); 
			    this.issueService.update(issue);  
				
			}
			return issueTopForm.getIssueId();
		}
		

	 
}


